/**
 * 会员管理控制器
 * @module controllers/membership
 */

const Membership = require('../models/membership.model');
const logger = require('../utils/logger');
const { createError } = require('../utils/error');

/**
 * 获取所有会员计划
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.getAllPlans = async (req, res, next) => {
  try {
    const plans = await Membership.getAllPlans();
    res.status(200).json({
      success: true,
      data: plans
    });
  } catch (err) {
    logger.error(`获取会员计划失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '获取会员计划失败'));
  }
};

/**
 * 获取用户会员状态
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.getUserMembershipStatus = async (req, res, next) => {
  try {
    // 获取当前用户ID
    const userId = req.user.id;
    
    const membershipStatus = await Membership.getUserMembershipStatus(userId);
    
    if (!membershipStatus) {
      return next(createError(404, '用户不存在'));
    }
    
    res.status(200).json({
      success: true,
      data: membershipStatus
    });
  } catch (err) {
    logger.error(`获取用户会员状态失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '获取用户会员状态失败'));
  }
};

/**
 * 升级到专业版
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.upgradeToPro = async (req, res, next) => {
  try {
    // 获取当前用户ID
    const userId = req.user.id;
    
    // 从请求体获取支付信息
    const { planId, paymentMethod, orderId } = req.body;
    
    // 验证planId是否存在
    const plan = await Membership.getPlanById(planId);
    if (!plan) {
      return next(createError(400, '无效的会员计划'));
    }
    
    // 计算专业版过期时间（根据计划周期）
    const now = new Date();
    let expiryDate = new Date(now);
    
    switch (plan.billingCycle) {
      case 'monthly':
        expiryDate.setMonth(now.getMonth() + 1);
        break;
      case 'quarterly':
        expiryDate.setMonth(now.getMonth() + 3);
        break;
      case 'annually':
        expiryDate.setFullYear(now.getFullYear() + 1);
        break;
      default:
        expiryDate.setMonth(now.getMonth() + 1);
        break;
    }
    
    // 记录交易
    const transactionData = {
      userId,
      planId,
      amount: plan.price,
      currency: plan.currency,
      status: 'completed',
      paymentMethod,
      orderId
    };
    
    const transaction = await Membership.recordTransaction(transactionData);
    
    // 更新用户会员状态
    const membershipData = {
      isPro: true,
      proExpiryDate: expiryDate.toISOString()
    };
    
    const updatedStatus = await Membership.updateUserMembership(userId, membershipData);
    
    res.status(200).json({
      success: true,
      message: '成功升级到专业版',
      data: {
        membershipStatus: updatedStatus,
        transaction
      }
    });
  } catch (err) {
    logger.error(`升级到专业版失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '升级到专业版失败'));
  }
};

/**
 * 取消专业版
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.cancelPro = async (req, res, next) => {
  try {
    // 获取当前用户ID
    const userId = req.user.id;
    
    // 检查用户是否是专业版
    const currentStatus = await Membership.getUserMembershipStatus(userId);
    
    if (!currentStatus) {
      return next(createError(404, '用户不存在'));
    }
    
    if (!currentStatus.isPro) {
      return next(createError(400, '用户不是专业版会员'));
    }
    
    // 更新用户会员状态
    const membershipData = {
      isPro: false,
      proExpiryDate: null
    };
    
    const updatedStatus = await Membership.updateUserMembership(userId, membershipData);
    
    res.status(200).json({
      success: true,
      message: '已成功取消专业版',
      data: updatedStatus
    });
  } catch (err) {
    logger.error(`取消专业版失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '取消专业版失败'));
  }
};

/**
 * 获取用户交易记录
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.getUserTransactions = async (req, res, next) => {
  try {
    // 获取当前用户ID
    const userId = req.user.id;
    
    // 获取分页参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    const result = await Membership.getUserTransactions(userId, page, limit);
    
    res.status(200).json({
      success: true,
      data: result.transactions,
      pagination: result.pagination
    });
  } catch (err) {
    logger.error(`获取用户交易记录失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '获取用户交易记录失败'));
  }
};

/**
 * 管理员: 获取所有交易记录
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.getAllTransactions = async (req, res, next) => {
  try {
    // 验证用户是否是管理员
    if (!req.user.isAdmin) {
      return next(createError(403, '无权限访问'));
    }
    
    // 获取分页参数
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    
    // 计算偏移量
    const offset = (page - 1) * limit;
    
    const db = new (require('sqlite3').verbose()).Database(require('../config/config').dbPath);
    
    // 查询总记录数
    db.get('SELECT COUNT(*) as count FROM transactions', [], (err, countResult) => {
      if (err) {
        db.close();
        logger.error(`获取交易记录数量失败: ${err.message}`, { stack: err.stack });
        return next(createError(500, '获取交易记录失败'));
      }
      
      const total = countResult.count;
      const pages = Math.ceil(total / limit);
      
      // 查询交易记录
      db.all(
        `SELECT t.*, u.username, m.name as plan_name 
         FROM transactions t
         LEFT JOIN users u ON t.user_id = u.id
         LEFT JOIN membership_plans m ON t.plan_id = m.id
         ORDER BY t.created_at DESC
         LIMIT ? OFFSET ?`,
        [limit, offset],
        (err, rows) => {
          db.close();
          
          if (err) {
            logger.error(`获取交易记录失败: ${err.message}`, { stack: err.stack });
            return next(createError(500, '获取交易记录失败'));
          }
          
          // 格式化结果
          const transactions = rows.map(row => {
            return {
              id: row.id,
              userId: row.user_id,
              username: row.username,
              planId: row.plan_id,
              planName: row.plan_name || '未知计划',
              amount: row.amount,
              currency: row.currency,
              status: row.status,
              paymentMethod: row.payment_method,
              createdAt: row.created_at,
              orderId: row.order_id
            };
          });
          
          // 返回交易记录和分页信息
          res.status(200).json({
            success: true,
            data: transactions,
            pagination: {
              page,
              limit,
              total,
              pages
            }
          });
        }
      );
    });
  } catch (err) {
    logger.error(`获取所有交易记录失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '获取所有交易记录失败'));
  }
};

/**
 * 管理员: 更新会员计划
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件函数
 */
exports.updatePlan = async (req, res, next) => {
  try {
    // 验证用户是否是管理员
    if (!req.user.isAdmin) {
      return next(createError(403, '无权限访问'));
    }
    
    const planData = req.body;
    
    // 验证必要字段
    if (!planData.id || !planData.name || planData.price === undefined) {
      return next(createError(400, '缺少必要字段'));
    }
    
    // 更新会员计划
    const updatedPlan = await Membership.upsertPlan(planData);
    
    res.status(200).json({
      success: true,
      message: '会员计划更新成功',
      data: updatedPlan
    });
  } catch (err) {
    logger.error(`更新会员计划失败: ${err.message}`, { stack: err.stack });
    next(createError(500, '更新会员计划失败'));
  }
}; 